package com.javachmapi.weixinlogin.controller;

import com.javachmapi.weixinlogin.auth.AccessToken;
import com.javachmapi.weixinlogin.config.APIConfig;
import com.javachmapi.weixinlogin.constant.CookieConstant;
import com.javachmapi.weixinlogin.constant.RedisConstant;
import com.javachmapi.weixinlogin.entity.User;
import com.javachmapi.weixinlogin.entity.WechatUserInfo;
import com.javachmapi.weixinlogin.service.UserService;
import com.javachmapi.weixinlogin.utils.AesUtil;
import com.javachmapi.weixinlogin.utils.CookieUtil;
import com.javachmapi.weixinlogin.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * (User)表控制层
 *
 * @author 宋利军
 * @since 2020-05-27 04:01:15
 */
@Slf4j
@Controller
@RequestMapping("/user/wechat")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 重定向至微信扫码界面
     */
    @GetMapping("/qrConnect")
    public String qrConnect() {
        log.info("正在进入qrConnect方法当中····");
        Map<String, String> wechatLoginUrl = userService.wechatLoginUrl();
        String url = wechatLoginUrl.get("url");
        return "redirect:" + url;
    }


    /**
     * 通过code获取
     */
    @GetMapping("/callback")
    @ResponseBody
    public User callback(HttpServletResponse response,
                            @RequestParam("code") String code,
                            @RequestParam("state") String state) {
        log.info("正在进入callback方法当中····");
        WechatUserInfo wechatUserInfo = null;
        User user = null;
        if (code != null && state != null) {
            // 验证state为了用于防止跨站请求伪造攻击
            String decrypt = AesUtil.decrypt(AesUtil.parseHexStr2Byte(state), AesUtil.PASSWORD_SECRET_KEY, 16);
            if (!decrypt.equals( APIConfig.PWD_MD5 + DateUtils.getYYYYMMdd())) {
                return null;
            }
            AccessToken access = userService.getAccessToken(code);
            if (access.getAccess_token() == null) {
                return null; //表示获取token失败
            }
            //1. openid去和数据库里的数据匹配
            user = userService.findUserByOpenid(access.getOpenid());
            if (user == null) {
                user = new User();
                //注册
                wechatUserInfo = userService.getWechatUserInfo(access.getAccess_token(),access.getOpenid());
                log.info(wechatUserInfo.toString());
                user.setName(wechatUserInfo.getNickname());
                user.setOpenId(access.getOpenid());
                user.setIcon(wechatUserInfo.getHeadimgurl());
                user.setCreateTime(new Date());
                user.setUpdateTime(new Date());
                user.setState(0);
                userService.save(user);
                log.info("注册存表完成！");
            }
            //2. 设置token至redis
            String token = access.getAccess_token();
            Integer expire = RedisConstant.EXPIRE;
            redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token), access.getOpenid(), expire, TimeUnit.SECONDS);
            //3. 设置token至cookie
            CookieUtil.set(response, CookieConstant.TOKEN, token, expire);
        }
        return user;
    }
}